<template>
  <div class="list">
    <sidebar v-model="active" @change="onChange" class="left">
      <sidebar-item
        v-for="i in carts"
        :key="i.id"
        :title="i.name"
        :to="{ name: 'list', query: { c_id: i.id } }"
      />
    </sidebar>
    <div class="right">
      <pull-refresh v-model="refreshing" @refresh="onRefresh">
        <List
          :finished="finished"
          :loading="loading"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <card
            v-for="i in list"
            :num="i.amount"
            :price="i.price.toFixed(2)"
            :desc="i.desc"
            :title="i.name"
            :thumb="urlImg(i.coverImage)"
            @click-thumb="clickThumb(i.id)"
          />
        </List>
        <cell v-for="item in str" :key="item" :title="item" />
      </pull-refresh>

      <!-- loadData一定要加()不然下方商品分类id会被覆盖 -->
      <!-- 点击加更多后传入当前商品分类id -->
    </div>
  </div>
</template>
<script setup>
import { ref, computed } from "vue";
import { Sidebar, SidebarItem, List, Card, PullRefresh } from "vant";
import { useRouter } from "vue-router";
import { userCartAPI } from "../services/auth";
import { urlImg } from "../uitils/urlImg";
import { onBeforeRouteUpdate, useRoute } from "vue-router";
// 商品列表的渲染
import { useProduct } from "../services/auth";
const router = useRouter();
const { list, loadData, loading, finished } = useProduct();
const { carts } = userCartAPI();
// 设置可穿参数的路由userote
const route = useRoute();
// 储存分类id,当前的分类id
const listId = ref(route.query.c_id);
// 初始化的时候调用loadData传入商品分类id
loadData(listId.value);

// 监听事件获取商品分类
onBeforeRouteUpdate((to, from) => {
  listId.value = to.query.c_id;
  loadData(to.query.c_id, true);
});
// 加载更多
const onLoad = () => {
  // 初始化的时候调用loadData传入商品分类id
  loadData(listId.value);
};

// 选中的分类值,通过计算属性来获取
const active = computed(() => {
  return carts.value.findIndex((item) => item.id == listId.value);
});
// 跳转详情页 并携带参数
const clickThumb = (id) => {
  router.push({
    name: "item",
    query: {
      id,
    },
  });
};
</script>
<style scoped lang="scss">
.list {
  display: flex;
  left: auto;
  .right {
    flex: 1;
    overflow: auto;
    margin-left: 5px;
  }
}
</style>
